package com.dongdongqiang.daogenerator.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * POJO工具类
 * Created by ZZB on 2017/9/26.
 */
public class POJOUtils {

    /**通过get方法获取对象值*/
    public static Object readDeclaredFieldByGetMethod(Object o , String fieldName) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = obtainGetMethod(o, fieldName);
        return method.invoke(o);
    }

    public static void writeDeclaredFieldBySetMethod(Object o , String fieldName, Object value) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = obtainSetMethod(o,fieldName);
        method.invoke(o,value);
    }

    /**获取对象属性的Get方法*/
    public static Method obtainGetMethod(Object o ,String fieldName) throws NoSuchFieldException, NoSuchMethodException {
        String fieldNameUpperCaseFirst = upperCaseFirst(fieldName);
        Class<?> aClass = o.getClass();
        Field field = aClass.getDeclaredField(fieldName);
        String getMethodStr = "get" + fieldNameUpperCaseFirst;
        Method getMethod = null;
        try {
            getMethod = aClass.getDeclaredMethod(getMethodStr);
        } catch (NoSuchMethodException e) {
            if(field.getType() .equals( Boolean.class) || field.getType() .equals( boolean.class) ){
                getMethodStr = "is" + fieldNameUpperCaseFirst;
                getMethod = aClass.getDeclaredMethod(getMethodStr);
            }
        }
        return getMethod;
    }

    /**获取对象属性的Get方法*/
    public static Method obtainSetMethod(Object o ,String fieldName) throws NoSuchFieldException, NoSuchMethodException {
        String fieldNameUpperCaseFirst = upperCaseFirst(fieldName);
        Class<?> aClass = o.getClass();
        Field field = aClass.getDeclaredField(fieldName);
        String setMethodStr = "set" + fieldNameUpperCaseFirst;
        Method setMethod = null;
        setMethod = aClass.getDeclaredMethod(setMethodStr,field.getType());
        return setMethod;
    }

    /**大写第一个字母*/
    public static String upperCaseFirst (String str) {
        if(str.length() >= 2){
            char c = str.charAt(0);
            char c1 = str.charAt(1);
            if(c >= 'a' && c <= 'z' && c1 >='A' && c1 <='Z' )
                return str;
        }
        return str.substring(0,1).toUpperCase() + str.substring(1,str.length() );
    }
}
